package client.comm.baoding.fragment

import android.content.Intent
import android.util.Log
import android.view.View
import androidx.core.view.ViewCompat
import androidx.lifecycle.Observer
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import client.comm.baoding.R
import client.comm.baoding.adapter.HomeTjGoodAdapter
import client.comm.baoding.adapter.SyPagingHeaderAdapter
import client.comm.baoding.api.bean.CateGoods
import client.comm.baoding.api.bean.GoodsIndex
import client.comm.baoding.dialog.CommImgDialog
import client.comm.baoding.dialog.JyInputPwdDialog
import client.comm.baoding.dialog.MsgTitleDialog
import client.comm.baoding.ui.AddrMangerActivity
import client.comm.baoding.ui.GoodsOrderActivity
import client.comm.baoding.ui.GylGoodsListActivity
import client.comm.baoding.ui.MainActivity
import client.comm.baoding.ui.MxJlActivity
import client.comm.baoding.ui.MyGuaDan2Activity
import client.comm.baoding.ui.MyZcActivity
import client.comm.baoding.ui.SearchActivity
import client.comm.baoding.ui.TdActivity
import client.comm.baoding.ui.TuiGuangActivity
import client.comm.baoding.ui.TxActivity
import client.comm.baoding.ui.Zz2Activity
import client.comm.baoding.ui.ZzActivity
import client.comm.baoding.ui.me.RealNameVerifyActivity
import client.comm.baoding.ui.vm.MainViewModel
import client.comm.commlib.base.BaseActivity
import client.comm.commlib.base.BaseFragment
import client.comm.commlib.base.PagerFooterAdapter
import client.comm.commlib.comm_ui.ImageGalleryActivity
import client.comm.commlib.comm_ui.WebActivity
import client.comm.commlib.comm_ui.draw.SpaceGridItemDecoration
import client.comm.commlib.dipToPx
import client.comm.commlib.network.data.PagingJsonResult
import client.comm.commlib.utils.Util
import client.comm.commlib.widget.EmptyLayout
import kotlinx.coroutines.launch

class TabOneItemFragment :
    BaseFragment<client.comm.baoding.databinding.FragmentTaboneBinding, MainViewModel>() {

    var goodsIndex: GoodsIndex? = null

    override fun getViewId(): Int {
        return R.layout.fragment_tabone
    }

    val adapter: HomeTjGoodAdapter by lazy {
        HomeTjGoodAdapter(requireContext(), mImgLoader).apply {
            refreshLoading = {
//                if (itemCount == 0) {
//                    binding.emptyLayout.errorType = EmptyLayout.NETWORK_LOADING
//                }
            }
            refreshNotLoading = {
                binding.refreshLayout.isRefreshing = false
//                if (itemCount == 0) {
//                    binding.emptyLayout.errorType = EmptyLayout.NODATA
//                } else {
//                    binding.emptyLayout.visibility = View.GONE
//                }

            }
            refreshError = {
                if (itemCount == 0)
                    binding.emptyLayout.errorType = EmptyLayout.NETWORK_ERROR
            }

        }

    }
    var scrollY: Float = 0.0f

    val headerAdapter: SyPagingHeaderAdapter by lazy {
        SyPagingHeaderAdapter(mImgLoader, requireActivity()).apply {
            tabCli = {
                if (headerAdapter.goodsIndex!!.category_list_index[it].category_id.equals("100")) {
                    requireContext().startActivity(
                        Intent(
                            requireContext(), GylGoodsListActivity::class.java
                        )
                    )
                } else viewModel.homeTabIndex.value = it
            }

            cateCli = {
                viewModel.cutOneTabId.value = "${it.category_id}"
                viewModel.switchValue.value = 1
            }
            runMsg = {
                viewModel.getCommImg()
            }
            locationCli = {
                (requireActivity() as MainActivity).privacyCompliance()
                startActivity(Intent(requireContext(), AddrMangerActivity::class.java))
            }
        }
    }

    override fun initViewModel(): MainViewModel = createViewModel()

    override fun initWidget() {
        binding.event = this
        initRv()
        viewModel.location.observe(this, {
            headerAdapter.setCity(it)
        })
        (requireActivity() as MainActivity).privacyCompliance()
//        getMsg()
    }

    val footer by lazy {
        PagerFooterAdapter()
    }

    val hengDecoration by lazy {
        SpaceGridItemDecoration(dipToPx(resources, 10.0f).toInt(), true)
    }

    private fun initRv() {

        Util.setBg(resources!!.getColor(R.color.tranplant), requireActivity().window)
        val controller = ViewCompat.getWindowInsetsController(binding.root)
        controller?.isAppearanceLightStatusBars = true
        val h = Util.getStatusBarHeight(requireContext())
        val p = binding.statusBar.layoutParams
        p.height = h
        binding.statusBar.layoutParams = p

        val gridLayoutManager =
            StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL).apply {

            }

        binding.recyclerView.layoutManager = gridLayoutManager
        binding.recyclerView.addItemDecoration(hengDecoration)
        binding.recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {

            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                scrollY += dy

                val he = headerAdapter.he
                Log.d("DDD", "scrollY$scrollY")
                // 1359
                if (scrollY > he) {
                    if (binding.tabLayoutAnim.visibility != View.VISIBLE) binding.tabLayoutAnim.visibility =
                        View.VISIBLE

//                    binding.tabLayoutAnim.translationY = 0.0f
                } else {
                    binding.tabLayoutAnim.visibility = View.GONE

//                    binding.tabLayoutAnim.translationY = he - scrollY
                }
            }


        })
        binding.recyclerView.adapter = adapter.withLoadStateHeaderAndFooter(
            header = headerAdapter, footer = footer
        )

        binding.refreshLayout.setOnRefreshListener {
            viewModel.goods_index_p()
        }
        binding.emptyLayout.setOnClickListener {
            viewModel.goods_index_p()
        }

        viewModel.homeTabIndex.observe(this, Observer {
            headerAdapter.notifyTab(it)
            when (it) {
                0 -> {
                    binding.tabOne.isSelected = true
                    binding.tabTwo.isSelected = false
                    binding.tabThree.isSelected = false
                    binding.tabFour.isSelected = false
                }

                1 -> {
                    binding.tabOne.isSelected = false
                    binding.tabTwo.isSelected = true
                    binding.tabThree.isSelected = false
                    binding.tabFour.isSelected = false

                }

                2 -> {
                    binding.tabOne.isSelected = false
                    binding.tabTwo.isSelected = false
                    binding.tabThree.isSelected = true
                    binding.tabFour.isSelected = false
                }

                3 -> {
                    binding.tabOne.isSelected = false
                    binding.tabTwo.isSelected = false
                    binding.tabThree.isSelected = false
                    binding.tabFour.isSelected = true
                }
            }
            adapter.refresh()
        })

    }

    override fun initData() {
        viewModel.homeCall.observe(this, Observer {
            it?.let {
                if (it.isSuccess) {
                    binding.emptyLayout.visibility = View.GONE
                    it.data?.let {
                        headerAdapter.goodsIndex = it
                        adapter.banner_list = it.mall_banner

                        headerAdapter.notifyDataSetChanged()
                        if (it.category_list_index.size > 0) binding.tabOne.text =
                            it.category_list_index[0].name
                        if (it.category_list_index.size > 1) binding.tabTwo.text =
                            it.category_list_index[1].name
                        if (it.category_list_index.size > 2) binding.tabThree.text =
                            it.category_list_index[2].name
                        if (it.category_list_index.size > 3) binding.tabFour.text =
                            it.category_list_index[3].name
                        if (viewModel.homeInit.value!! == true) {
                            adapter.refresh()
                        } else
                            getGoodsIndex()
                    }
                }
            }
        })
        viewModel.homeInit.value = false
        viewModel.goods_index_p()
        viewModel.CommImgRet.observe(this, Observer {
            it?.let {
                if (it != null && it.isSuccess) {
                    val imgg = it.data!!
                    viewModel.CommImgRetSucc.value = true
                    if (imgg.img_list.size > 0) {
                        val status = imgg.img_list[0].show_status
                        CommImgDialog(requireActivity() as BaseActivity<*, *>).apply {
                            commImg = imgg
                            click = {
                                val b = it
                                if (!b.big_img.isNullOrEmpty()) {
                                    ImageGalleryActivity.show(
                                        requireContext(), b.big_img, true, false
                                    )
                                } else if (!b.url.isNullOrEmpty()) {
                                    context.startActivity(Intent(
                                        context, WebActivity::class.java
                                    ).apply {
                                        putExtra("adInfo", b.url)
                                        putExtra("title", b.title)
                                    })
                                } else {
                                    when (b.link_name) {
                                        "我的订单" -> {
                                            startActivity(Intent(
                                                context, GoodsOrderActivity::class.java
                                            ).apply {
                                                putExtra("index", 0)
                                            })
                                        }

                                        "待支付" -> {
                                            startActivity(Intent(
                                                context, GoodsOrderActivity::class.java
                                            ).apply {
                                                putExtra("index", 1)
                                            })
                                        }

                                        "待发货" -> {
                                            startActivity(Intent(
                                                context, GoodsOrderActivity::class.java
                                            ).apply {
                                                putExtra("index", 2)
                                            })
                                        }

                                        "待收货" -> {
                                            startActivity(Intent(
                                                context, GoodsOrderActivity::class.java
                                            ).apply {
                                                putExtra("index", 3)
                                            })
                                        }

                                        "已完成" -> {
                                            startActivity(Intent(
                                                context, GoodsOrderActivity::class.java
                                            ).apply {
                                                putExtra("index", 4)
                                            })
                                        }

                                        "充值" -> {
                                            viewModel.getRechargeOrder()
                                        }

                                        "转出" -> {
                                            startActivity(Intent(context, TxActivity::class.java))
                                        }

                                        "地址管理" -> {
                                            startActivity(
                                                Intent(
                                                    context, AddrMangerActivity::class.java
                                                )
                                            )
                                        }

                                        "我的好友圈" -> {
                                            startActivity(Intent(
                                                context, TdActivity::class.java
                                            ).apply {})
                                        }

                                        "明细记录" -> {
                                            startActivity(Intent(context, MxJlActivity::class.java))
                                        }

                                        "我的挂单" -> {
                                            startActivity(Intent(
                                                context, MyGuaDan2Activity::class.java
                                            ).apply {
                                                putExtra("goodsId", "") //it.goods_info.goods_id
                                            })
                                        }

                                        "邀请好友" -> {
                                            startActivity(
                                                Intent(
                                                    context, TuiGuangActivity::class.java
                                                )
                                            )
                                        }

                                        "我的资产" -> {
                                            startActivity(Intent(context, MyZcActivity::class.java))
                                        }

                                        "转账" -> {
                                            startActivity(Intent(context, ZzActivity::class.java))
                                        }

                                        "批发商入口" -> {
                                            JyInputPwdDialog(requireContext()).apply {
                                                ok = {
                                                    viewModel.valiPayPwd(it)
                                                }
                                                okTxt = "确认"
                                                cancleTxt = "取消"
                                            }.show()
                                        }

                                        "兑换" -> {
                                            startActivity(Intent(context, Zz2Activity::class.java))

                                        }

                                        "绑定" -> {
//                                            startActivity(
//                                                Intent(
//                                                    context, BindJysActivity::class.java
//                                                )
//                                            )
                                        }

                                        "实名认证" -> {
                                            startActivity(
                                                Intent(
                                                    context, RealNameVerifyActivity::class.java
                                                )
                                            )
                                        }

                                    }
                                }

                                cancel()
//                                if (status == 1) {
//                                    requireActivity().finish()
//                                }
                            }
                            this.status = status
                        }.show()
                    }
                    viewModel.CommImgRet.value = null
                } else {
                    MsgTitleDialog(requireActivity()).apply {
                        title = "获取公告失败，请重新获取"
                        okTxt = "重新获取"
                        cancleTxt = "退出"
                        cancle = {
                            requireActivity().finish()
                        }
                        setCancelable(false)
                        setCanceledOnTouchOutside(false)
                        ok = {
                            getMsg()
                        }
                    }.show()
                }
            }
        })
    }

    fun tabClick(i: Int) {
        if (headerAdapter.goodsIndex!!.category_list_index[i].category_id.equals("100")) {
            requireContext().startActivity(
                Intent(
                    requireContext(), GylGoodsListActivity::class.java
                )
            )
        } else viewModel.homeTabIndex.value = i
    }


    fun goSearch() {
        startActivity(Intent(requireContext(), SearchActivity::class.java))
    }

    //购物车
    fun onShopCart(position: Int) {
        changeMainTab?.invoke(position)
    }

    private fun getGoodsIndex() {
        viewModel.homeInit.value = true
        lifecycleScope.launch {

            viewModel.pagingDataAuto(20, hold = {


                val ret = viewModel.server.goods_type_detail(
                    it,
                    "${headerAdapter.goodsIndex!!.category_list_index[viewModel.homeTabIndex.value!!].category_id}"
                ).body()
//                ret?.let {
//                    withContext(Dispatchers.Main) {
//                        headerAdapter.goodsIndex = it.data
//                        headerAdapter.notifyDataSetChanged()
//                    }
//                }
                val list = ArrayList<CateGoods.Goods>()
                if (it == 1) {
//                    binding.tabLayoutAnim.visibility = View.GONE
                    scrollY = binding.recyclerView.computeVerticalScrollOffset().toFloat()

                    ret?.data?.goods_list?.let {
                        if (it.size > 0) {
                            if (adapter.banner_list != null && adapter.banner_list!!.size > 0) {
                                val g = CateGoods.Goods(
                                    create_time = "",
                                    fees = "",
                                    goods_id = "",
                                    goods_img = "",
                                    goods_status = 0,
                                    name = "112233",
                                    token = "",
                                    old_price = "",
                                    price = 0.0,
                                    lpq_price = 0.0,//体验券
                                    integral = 0.0,
                                    priority = 0,
                                    stock_c = 0,
                                    sku_status = 0, // 1 就是供应链
                                    sales = "",
                                    sku = "",
                                    goods_label = arrayListOf()
                                )
                                list.add(g)
                            }


                            list.addAll(it)
                        }
                    }

                } else {
                    ret?.data?.goods_list?.let {
                        if (it.size > 0) {
                            list.addAll(it)
                        }
                    }
                }
                PagingJsonResult(
                    list = list, code = ret?.code, message = ret?.message
                )
            }).collect {
                adapter.submitData(it)
            }
        }
    }

    fun tuiguang() {
        requireContext().startActivity(Intent(context, TuiGuangActivity::class.java))
    }

    var changeMainTab: ((position: Int) -> Unit)? = null
    var notice: ((ArrayList<GoodsIndex.Article>) -> Unit)? = null


    fun goNotice() {
        notice?.invoke(goodsIndex!!.article_list)
    }

    fun getMsg() {
        if (!viewModel.CommImgRetSucc.value!!) viewModel.getCommImg()
    }


}